from flask import Flask, make_response, jsonify, g, current_app as app,Blueprint,request
from sqlalchemy import select,insert,update,func,join
from sqlalchemy.sql import text
from eim.tools.searchtool import SearchCondition,SearchConditionList,MatchLogic,PartnerRS
from eim.tools.dbtool import DBTool
from eim import db
from eim.result.simple_result import SimpleResult

userbp=Blueprint("userprinter","userprinter",__name__,url_prefix='/user')

# 添加新的操作员
@userbp.route("/appendUser",methods=["PUT"])
def appendNewUser():
    """
    添加新的操作员
    """
    try:
        params = request.json
        if(not isinstance(params,dict)):
            raise Exception('参数样式不正确,请保证参数样式为json')
        if('name' not in params.keys()) or ('password' not in params.keys()):
            raise Exception('调用增加操作员接口时缺少必要的参数,请对照文档调整参数')
        from eim.Services.userService import UserService
        dbtool = DBTool(db)
        uno = dbtool.getNewCode("userinfo","U","",8)
        us = UserService(db)
        id = us.appendUser(uno,params["workno"],params["name"],params["password"],params["pcode"],params["rolecode"])
        return SimpleResult(status="T",value=str(id)).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(es)
        return SimpleResult(msg=info).toDict()

# 根据id更新员工信息  
@userbp.route("/upgrade/<id>",methods=["POST"])
def userUpgrade(id:int):
    """
    根据id更新员工信息
    Args:
        id (int): 待更新信息的员工id
    """
    try:
        params = request.json
        if(not isinstance(params,dict)):
            raise Exception("参数样式不正确,请确保参数样式为json")
        if('usercode' in params.keys()):
            raise Exception("员工编码不能调整")
        
        from eim.Services.userService import UserService
        us = UserService(db)
        rowcount:int=us.updateUser(id,params)
        return SimpleResult(status='T',value=rowcount).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(es)
        return SimpleResult(msg=info).toDict()


# 根据id删除指定的操作员
@userbp.route("/deluser/<int:id>",methods=["DELETE"])
def deleteUser(id):
    """
    根据ID删除指定的操作员

    Args:
        id (_type_): 操作员id
    """
    try:
        from eim.Services.userService import UserService
        us = UserService(db)
        rc = us.deleteUser(id)
        return SimpleResult(status="T",value=rc).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()



# 根据id获取员工基础信息    
@userbp.route("/getOneUser/<int:id>",methods=["GET"])
def getOneUser(id):
    """
    根据id获取指定操作员的详细信息

    Args:
        id (_type_): 操作员id
    """
    try:
        from eim.Services.userService import UserService
        us = UserService(db)
        rc = us.getUserByID(id)
        return SimpleResult(status="T",value=rc).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()

@userbp.route("/login/<workno>/<pwd>",methods=["GET"])    
def userLogin(workno:str,pwd:str):
    """
    员工登录验证
    """
    try:
        x_forwarded_for = request.headers.get('X-Forwarded-For')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.remote_addr
        from eim.Services.userService import UserService
        us = UserService(db)
        rc = us.userLogin(workno,pwd,ip)
        token = us.createToken(rc["usercode"],rc["name"],rc["ID"],rc["workno"],rc["rolecode"],30)
        return SimpleResult(status="T",value=token).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
 
@userbp.route("/checkpwd/<int:uid>/<pwd>")   
def checkPwd(uid:int,pwd:str):
    """
    校验指定用户的登录密码  
    Args:
        uid (str): 用户id
        pwd (str): 用户密码
    """  
    try:
        from eim.Services.userService import UserService
        us = UserService(db)
        chkflag = us.checkpwd(uid,pwd)
        return SimpleResult(status="T",value=chkflag).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
        
    
    

@userbp.route("/page/<int:pn>/<int:ps>",methods=["POST"])
def pageUser(pn:int,ps:int):
    """
    分页检索操作员信息

    Args:
        pn (int): 分页页码
        ps (int): 分页页面尺寸
    """
    try:
        pms = request.json
        if(not isinstance(pms,dict)):
            raise Exception("请正确提交查询参数")
        if(not 'cols' in pms.keys()):
            raise Exception("参数中必须包含字段列表cols")
        if(not 'pms' in pms.keys()):
            raise Exception("参数中必须包含检索条件对象pms")
        
        slist = SearchConditionList()
        for item in pms["pms"]:
            cd = item["CD"]
            cdobj = SearchCondition(cd["field"],MatchLogic.from_Name(cd["logic"]),cd["value"])
            rs=PartnerRS.from_name(item["RS"])
            slist.appendCondition(rs,cdobj)
        
        from eim.Services.userService import UserService
        us = UserService(db)
        
        res = us.pageUsers(pn,ps,pms["cols"],slist)
        return SimpleResult(status="T",value=res).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    
@userbp.route("/chktoken/<tk>",methods=['GET'])
def checktoken(tk:str):
    """
    校验token

    Args:
        tk (str): token内容
    """
    import jwt
    try:
        s = jwt.decode(tk, app.secret_key, algorithms=['HS256'])
        return SimpleResult(status='T',value="").toDict()
    except Exception as err:
         return SimpleResult(msg=str(err)).toDict()
    
@userbp.route("/getUserInfoByToken/<tk>",methods=['GET'])
def getUserInfoFromToken(tk:str):
    """
    通过token获取登录信息

    Args:
        tk (str): token信息
    """
    import jwt
    try:
        s = jwt.decode(tk, app.secret_key, algorithms=['HS256'])["data"]
        return SimpleResult(status='T',value=s).toDict()
    except Exception as err:
         return SimpleResult(msg=str(err)).toDict()

@userbp.route("/batchDelUser",methods=["POST"])
def batchDelUser():
    """
    批量停用操作员
    """
    try:
        from eim.Services.userService import UserService
        us = UserService(db)
        pms = request.json
        ids:list = pms["ids"]
        if(len(ids)<2):
            ids.append(-1);
        rowcount=us.batchDelUser(tuple(ids))
        return SimpleResult(status='T',value=rowcount).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(f"批量停用操作员出错,错误详细信息为:{info}")
        return SimpleResult(msg=info).toDict()
    
@userbp.route("/batchActionUser",methods=["POST"])
def batchActionUser():
    """
    批量激活操作员
    """
    try:
        from eim.Services.userService import UserService
        us = UserService(db)
        pms = request.json
        ids:list = pms["ids"]
        if(len(ids)<2):
            ids.append(-1);
        rowcount=us.batchActionUser(tuple(ids))
        return SimpleResult(status='T',value=rowcount).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(f"批量激活操作员出错,错误详细信息为:{info}")
        return SimpleResult(msg=info).toDict()
 
@userbp.route("/batchResetPwd",methods=["POST"])   
def batchRestUserPwd():
    """
    批量修改操作员密码
    """
    try:
        from eim.Services.userService import UserService
        us= UserService(db)
        pms = request.json
        ids:list = pms["ids"]
        # 处理list转tuple单元素多逗号问题
        if(len(ids)<2):
            ids.append(-1)
        rowcount = us.batchResetPassword(tuple(ids),pms["pwd"])
        return SimpleResult(status="T",value=rowcount).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()